"""
视频上传相关
"""
import json
import os
import logging
import time
import traceback

from flask import Blueprint, request, g, make_response, send_from_directory

from flask_restful import Resource, Api, reqparse
from werkzeug.utils import secure_filename

from common.models import db
from common.models.user import UserBase
from common.models.video import Video
from common.utils.custom_output_json import custom_output_json
from common.utils.jwt_util import verify_jwt
from common.utils.utils import upload_file
from define.define import IP_PORT, BASE_URL

UPLOAD_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'static/video')

video_bp = Blueprint('video_bp', __name__, url_prefix='/file')
api = Api(video_bp)


@api.representation('application/json')
def output_json(data, code=200, headers=None):
    return custom_output_json(data, code, headers)


class UploadVideoByToken(Resource):
    """
    通过携带token上传视频
    """
    def post(self):
        try:
            # 获取appkey信息
            parser = reqparse.RequestParser()
            parser.add_argument('token', required=True)
            args = parser.parse_args()
            token = args.get('token')
            payload = verify_jwt(token)
            if not payload:
                return {'code': 500, 'message': 'token invalid'}
            appkey_id = payload.get('appkey_id')
            result = upload_file(appkey_id, request, UPLOAD_PATH)
            return result
        except:
            error = traceback.format_exc()
            logging.error('UploadVideoByToken error:{}'.format(error))
            return {'message': error, 'code': 500}


class UploadVideo(Resource):
    """
    上传视频
    """

    def post(self):
            # 获取appkey信息
        parser = reqparse.RequestParser()
        parser.add_argument('appkey_id', required=True)
        args = parser.parse_args()
        appkey_id = args.get('appkey_id')
        result = upload_file(appkey_id, request, UPLOAD_PATH)
        return result


class GetUploadFile(Resource):
    def get(self, filename):
        parser = reqparse.RequestParser()
        parser.add_argument('appkey_id', required=True)
        args = parser.parse_args()
        appkey_id = args.get('appkey_id')
        path = os.path.join(UPLOAD_PATH, appkey_id)
        return send_from_directory(path, filename)


api.add_resource(UploadVideo, '/upload_file', endpoint='upload_file')
api.add_resource(UploadVideoByToken, '/upload_file_by_token', endpoint='upload_file_by_token')
api.add_resource(GetUploadFile, '/video/<filename>')
